<template>
  <div class="employee-statistics">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>员工统计概览</span>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">员工总数</div>
                <div class="stat-value">{{ summaryData.totalEmployees }}</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">男性员工</div>
                <div class="stat-value">{{ summaryData.maleCount }}</div>
                <div class="stat-trend">
                  <span>{{ summaryData.malePercentage }}%</span>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">女性员工</div>
                <div class="stat-value">{{ summaryData.femaleCount }}</div>
                <div class="stat-trend">
                  <span>{{ summaryData.femalePercentage }}%</span>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-title">平均薪资</div>
                <div class="stat-value">¥{{ summaryData.avgSalary }}</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>部门员工分布</span>
            </div>
          </template>
          <div ref="pieChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>薪资分布</span>
            </div>
          </template>
          <div ref="barChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>性别分布</span>
            </div>
          </template>
          <div ref="genderPieChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>职位分布</span>
            </div>
          </template>
          <div ref="jobBarChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>员工入职时间分布</span>
              <div>
                <el-radio-group v-model="entryDateRange" size="small" @change="handleDateRangeChange">
                  <el-radio-button label="year">年</el-radio-button>
                  <el-radio-button label="month">月</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div ref="lineChart" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

const employees = ref([])
const summaryData = ref({
  totalEmployees: 0,
  maleCount: 0,
  femaleCount: 0,
  malePercentage: 0,
  femalePercentage: 0,
  avgSalary: 0
})

const entryDateRange = ref('year')

const pieChart = ref(null)
const barChart = ref(null)
const genderPieChart = ref(null)
const jobBarChart = ref(null)
const lineChart = ref(null)

// 从API获取员工数据
const fetchEmployees = async () => {
  try {
    const response = await axios.get('http://localhost:8080/emp')
    employees.value = response.data.data
    calculateSummaryData()
    renderCharts()
  } catch (error) {
    console.error('获取员工数据失败:', error)
  }
}

// 计算汇总数据
const calculateSummaryData = () => {
  const total = employees.value.length
  const males = employees.value.filter(emp => emp.gender === 1 || emp.gender === '1').length
  const females = employees.value.filter(emp => emp.gender === 2 || emp.gender === '2').length
  const totalSalary = employees.value.reduce((sum, emp) => sum + (emp.salary || 0), 0)
  
  summaryData.value = {
    totalEmployees: total,
    maleCount: males,
    femaleCount: females,
    malePercentage: total > 0 ? ((males / total) * 100).toFixed(1) : 0,
    femalePercentage: total > 0 ? ((females / total) * 100).toFixed(1) : 0,
    avgSalary: total > 0 ? (totalSalary / total).toFixed(0) : 0
  }
}

// 渲染所有图表
const renderCharts = () => {
  renderPieChart()
  renderBarChart()
  renderGenderPieChart()
  renderJobBarChart()
  renderLineChart()
}

// 部门分布饼图
const renderPieChart = () => {
  // 按部门统计员工数量
  const deptMap = {}
  employees.value.forEach(emp => {
    const deptName = getDeptName(emp.deptId)
    if (!deptMap[deptName]) {
      deptMap[deptName] = 0
    }
    deptMap[deptName]++
  })

  const chart = echarts.init(pieChart.value)
  const option = {
    title: {
      text: '部门员工占比',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: Object.keys(deptMap)
    },
    series: [
      {
        name: '员工数量',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: Object.keys(deptMap).map(dept => ({
          value: deptMap[dept],
          name: dept
        }))
      }
    ]
  }
  chart.setOption(option)
  
  window.addEventListener('resize', function() {
    chart.resize()
  })
}

// 薪资分布柱状图
const renderBarChart = () => {
  // 薪资区间统计
  const salaryRanges = [
    { range: '5k以下', min: 0, max: 5000 },
    { range: '5k-10k', min: 5000, max: 10000 },
    { range: '10k-15k', min: 10000, max: 15000 },
    { range: '15k-20k', min: 15000, max: 20000 },
    { range: '20k以上', min: 20000, max: Infinity }
  ]
  
  const salaryData = salaryRanges.map(range => {
    const count = employees.value.filter(emp => 
      emp.salary >= range.min && emp.salary < range.max
    ).length
    return { range: range.range, count }
  })

  const chart = echarts.init(barChart.value)
  const option = {
    title: {
      text: '员工薪资分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: salaryData.map(item => item.range),
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [
      {
        name: '人数',
        type: 'bar',
        barWidth: '60%',
        data: salaryData.map(item => item.count),
        itemStyle: {
          color: function(params) {
            const colorList = ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE']
            return colorList[params.dataIndex % colorList.length]
          }
        }
      }
    ]
  }
  chart.setOption(option)
  
  window.addEventListener('resize', function() {
    chart.resize()
  })
}

// 性别分布饼图
const renderGenderPieChart = () => {
  const maleCount = employees.value.filter(emp => emp.gender === 1 || emp.gender === '1').length
  const femaleCount = employees.value.filter(emp => emp.gender === 2 || emp.gender === '2').length
  const otherCount = employees.value.length - maleCount - femaleCount

  const chart = echarts.init(genderPieChart.value)
  const option = {
    title: {
      text: '性别分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['男', '女']
    },
    series: [
      {
        name: '性别分布',
        type: 'pie',
        radius: '70%',
        center: ['50%', '60%'],
        data: [
          { value: maleCount, name: '男', itemStyle: { color: '#5470C6' } },
          { value: femaleCount, name: '女', itemStyle: { color: '#EE6666' } }   
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          formatter: '{b}: {c} ({d}%)'
        }
      }
    ]
  }
  chart.setOption(option)
  
  window.addEventListener('resize', function() {
    chart.resize()
  })
}

// 职位分布柱状图
const renderJobBarChart = () => {
  // 职位映射
  const jobMap = {
    1: '项目经理',
    2: '前端开发',
    3: '后端开发',
    4: 'UI设计师',
    5: '测试工程师',
    6: '产品经理',
    7: '数据分析师',
    8: '运维工程师'
  }
  
  // 按职位统计员工数量
  const jobCount = {}
  employees.value.forEach(emp => {
    const jobName = jobMap[emp.job] || `未知职位${emp.job}`
    if (!jobCount[jobName]) {
      jobCount[jobName] = 0
    }
    jobCount[jobName]++
  })

  const chart = echarts.init(jobBarChart.value)
  const option = {
    title: {
      text: '职位分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: Object.keys(jobCount),
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [
      {
        name: '人数',
        type: 'bar',
        data: Object.values(jobCount),
        itemStyle: {
          color: function(params) {
            const colorList = ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE', '#3BA272', '#FC8452', '#9A60B4']
            return colorList[params.dataIndex % colorList.length]
          }
        }
      }
    ]
  }
  chart.setOption(option)
  
  window.addEventListener('resize', function() {
    chart.resize()
  })
}

// 入职时间分布折线图
const renderLineChart = () => {
  // 根据选择的时间范围生成不同的数据
  let xAxisData = []
  let seriesData = []
  
  if (entryDateRange.value === 'year') {
    // 按年统计
    const yearMap = {}
    employees.value.forEach(emp => {
      if (emp.entryDate) {
        const year = emp.entryDate.split('-')[0] + '年'
        if (!yearMap[year]) {
          yearMap[year] = 0
        }
        yearMap[year]++
      }
    })
    
    xAxisData = Object.keys(yearMap).sort()
    seriesData = xAxisData.map(year => yearMap[year])
  } else {
    // 按月统计
    const monthMap = {}
    employees.value.forEach(emp => {
      if (emp.entryDate) {
        const date = new Date(emp.entryDate)
        const month = `${date.getFullYear()}年${date.getMonth() + 1}月`
        if (!monthMap[month]) {
          monthMap[month] = 0
        }
        monthMap[month]++
      }
    })
    
    // 按时间排序
    const sortedMonths = Object.keys(monthMap).sort((a, b) => {
      return new Date(a.replace('年', '-').replace('月', '')) - 
             new Date(b.replace('年', '-').replace('月', ''))
    })
    
    // 最多显示12个月
    xAxisData = sortedMonths.slice(-12)
    seriesData = xAxisData.map(month => monthMap[month])
  }

  const chart = echarts.init(lineChart.value)
  const option = {
    title: {
      text: '员工入职时间分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData,
      axisLabel: {
        rotate: entryDateRange.value === 'month' ? 45 : 0
      }
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [
      {
        name: '入职人数',
        type: 'line',
        stack: 'Total',
        data: seriesData,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(58, 77, 233, 0.8)'
            },
            {
              offset: 1,
              color: 'rgba(58, 77, 233, 0.1)'
            }
          ])
        },
        itemStyle: {
          color: '#3a4de9'
        },
        smooth: true
      }
    ]
  }
  chart.setOption(option)
  
  window.addEventListener('resize', function() {
    chart.resize()
  })
}

// 部门ID到名称的映射
const getDeptName = (deptId) => {
  const deptMap = {
    1: '学工部',
    2: '教研部',
    3: '咨询部',
    4: '就业部',
    5: '人事部',
    6: '行政部',
    7: '综合部'
  }
  return deptMap[deptId] || `未知部门${deptId}`
}

const handleDateRangeChange = () => {
  renderLineChart()
}

onMounted(() => {
  fetchEmployees()
})
</script>

<style scoped>
.employee-statistics {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-card {
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
  text-align: center;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.stat-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-compare {
  color: #909399;
  margin-left: 5px;
}

.mt-20 {
  margin-top: 20px;
}
</style>